﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Orpheus.Analyzer
{
    public class PeakDetector
    {
        public static List<int> DetectPeakIndexes(double[] src, int startIndex, int endIndex)
        {
            var source = src.Skip(startIndex).Take(endIndex - startIndex).ToArray();

            var result = new List<int>();
            var average = source.Sum()/source.Length;
            var v = Math.Sqrt(source.Sum(x => Math.Pow(x - average, 2))/source.Length);

            var c = -0.0025714*v + 1.5142857;

            int peakStart = 0;
            int peakEnd = 0;
            int i = 0;
            while(i < source.Length)
            {
                if (source[i] > c)
                {
                    peakStart = i;
                    while (i < source.Length - 1 && source[i + 1] > c)
                    {
                        i++;
                    }
                    peakEnd = i + 1;

                    int peak = DetectPeak(source, peakStart, peakEnd);
                    result.Add(peak);
                }
            }

            return result;
        }


        private static int DetectPeak(double[] source, int startIndex, int endIndex)
        {
            int peakIndex = startIndex;

            for (int i = startIndex + 1; i < endIndex; i++)
            {
                if (source[i] > source[peakIndex])
                {
                    peakIndex = i;
                }
            }

            return peakIndex;
        }
    }
}
